//
//  ShopListViewController.m
//  rrbi
//
//  Created by mac book on 2018/12/4.
//

#import "ShopListViewController.h"
#import "ShopListTableViewCell.h"


@interface ShopListViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;

@property(nonatomic,strong) Pager* page;


@end

@implementation ShopListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.navigationItem.title =  @"店铺分类";
//    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    rightButton.backgroundColor = [UIColor greenColor];
//    rightButton.layer.cornerRadius = 5;
//    rightButton.frame = CGRectMake(0, 0, 60, 25);
//    [rightButton setTitle:@"添加分类" forState:UIControlStateNormal];
//    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    rightButton.titleLabel.font = kFontNameSize(14);
//    [rightButton addTarget:self action:@selector(rightButton) forControlEvents:UIControlEventTouchUpInside];
//    //添加到导航条
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(rightButton)];

    [self creatSubViews];
    
    [self refreshDataSource];
}

-(void)rightButton{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"添加分类" preferredStyle:UIAlertControllerStyleAlert];
    //定义第一个输入框；
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入分类名";
        
    }];
    //增加取消按钮；
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        UITextField *inputInfo = alertController.textFields.firstObject;
        if (inputInfo.text.length == 0) {
            ShowMessage(@"分类名不能为空!");
            return ;
        }else{

            NSDictionary* arg = @{@"ince":@"addshopcate",
                                  @"sid":[UserHandle shareInstance].userId,
                                  @"shopcate":inputInfo.text
                                  };
            [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
                NSLog(@"data = %@",data);
                NSInteger flag = [[data objectForKey:@"ret"]integerValue];
                if(flag == 200){
                    ShowMessage(@"添加成功");
                    //                self.page.pageIndex = 1;
                    [self getData];
                }else{
                    
                    ShowMessage([data objectForKey:@"msg"]);
                }
                
            } failure:^(NSError *error) {
                [self alertHUD:@"网络异常"];
            }];
            
            
        }
        
    }];
    
    
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];

    [self presentViewController:alertController animated:true completion:nil];
    
}

-(void)creatSubViews{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,  CGRectGetHeight(self.view.frame) -NAVGATIONBAR_HEIGHT) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];
    
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    
}

#pragma mark -  Data Source
-(void)getData{
    
    NSDictionary* arg = @{@"ince":@"addshopcate",
                          @"sid":[UserHandle shareInstance].userId,
//                          @"page":[WMHelper integerConvertToString:self.page.pageIndex]
                          };

    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        NSLog(@"店铺分类 = %@",data);
        
        NSInteger flag = [[data objectForKey:@"ret"]integerValue];
        
        if(flag == 200){
            
            NSArray* array = [data objectForKey:@"list"];
            self.dataArray = [StoreModel mj_objectArrayWithKeyValuesArray:array];
            [self.tableView reloadData];
            
            
        } else{
            [self alertHUD:[data objectForKey:@"msg"]];
        }
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSError *error) {
        [self alertHUD:@"网络异常"];
        [self.tableView.mj_header endRefreshing];
    }];
    
}
-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        weakSelf.page.pageIndex = 1;
        [weakSelf getData];
    }];
    
//    self.tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
//        weakSelf.page.pageIndex ++;
//        [weakSelf getData];
//    }];
    [self.tableView.mj_header beginRefreshing];
}




#pragma mark - ******* tableview代理方法 *******
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    static NSString *cellID = @"CELL_ID";
    
    ShopListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if(!cell){
        cell = [[ShopListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    StoreModel *model = self.dataArray[indexPath.row];
    cell.storeModel = model;
    cell.deleteBtnBlock = ^{
       
        NSDictionary* arg = @{@"ince":@"deleshopcate",
                              @"sid":[UserHandle shareInstance].userId,
                              @"scid":model.store_id
                              };
        [self showHUD];
        [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
            [self hidHUD];
            
            NSLog(@"data = %@",data);
            NSInteger flag = [[data objectForKey:@"ret"]integerValue];
            if(flag == 200){
                ShowMessage([data objectForKey:@"msg"]);
                //                self.page.pageIndex = 1;
                [self getData];
                
            }else{
                ShowMessage([data objectForKey:@"msg"]);
            }
            
        } failure:^(NSError *error) {
            [self hidHUD:@"网络异常"];
        }];
        
    };
    return cell;
    
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}





-(NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

-(Pager *)page{
    if(!_page){
        _page = [[Pager alloc]init];
        _page.pageIndex = 1;
    }
    return _page;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
